package com.jsoft.util;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.util.List;

/**
 * @author:sha
 * @email:o68o4741@163.com
 * @date:2023/2/21
 */
public class DAO<T> {

    private QueryRunner queryRunner = null;
    private Class<T> type;

    public DAO() {
        queryRunner = new QueryRunner(PoolUtil.getDataSource());
        // 获取当前类型的带有泛型类型的父类
        ParameterizedType ptClass = (ParameterizedType) this.getClass().getGenericSuperclass();
        // 获取运行期的泛型类型
        type = (Class<T>) ptClass.getActualTypeArguments()[0];
    }

    public <E> E getForValue(String sql, Object... args) throws Exception {
        return queryRunner.query(sql,new ScalarHandler<>(),args);
    }

    public List<T> getForList(String sql, Object... args) throws Exception {
        return queryRunner.query(sql,new BeanListHandler<>(type),args);
    }

    public T get(String sql, Object... args) throws Exception {
        return queryRunner.query(sql,new BeanHandler<>(type),args);
    }

    public int update(String sql, Object... args) throws Exception {
        return queryRunner.update(sql,args);
    }
    
    public int update(String sql, Connection connection, Object... args) throws Exception {
        return queryRunner.update(sql,connection,args);
    }
}
